package com.blockchain.securewallet;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.activities.AddressBookActivity;
import com.blockchain.securewallet.activities.SettingActivity;
import com.blockchain.securewallet.activities.TransationRecoderActivity;
import com.blockchain.securewallet.activities.UniversalActivity;
import com.blockchain.securewallet.activities.WalletInitActivity;
import com.blockchain.securewallet.adapter.CoinWalletAdapter;
import com.blockchain.securewallet.floatwindow.FloatWindowService;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.model.db.oper.AccountDaoOpe;
import com.blockchain.securewallet.tools.ActivityLauncher;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.ToastUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.main_coin_list_recycler_view)
    RecyclerView rvCoinList;

    private List<CoinWallet> wallets = null;
    CoinWalletAdapter adapter = null;
    private DrawerLayout drawer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        long walletCount = WalletApp.getInstance().getDaoSession().getCoinWalletDao().count();
        int walletCount = AccountDaoOpe.queryAll(this).size();

        if (walletCount == 0) {
            Intent intent = new Intent();
            intent.setClass(this, WalletInitActivity.class);
            startActivity(intent);
            finish();               // finish会调用到onDestroy方法
            return;   //防止finish()导致的不能阻止后面代码运行的问题

        } else {
//            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                requestDrawOverLays();
//            }else{
//                Intent floatIntent = new Intent(MainActivity.this, FloatWindowService.class);
//                startService(floatIntent);
//            }
        }

        //finish(); // 就算finish()直接写在这里，后面的代码还是会执行到 // onDestroy()也是...

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setOverflowIcon(null);
        toolbar.setTitle("主页");
        setSupportActionBar(toolbar);

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        
//        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
        PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "cn");
        mWakeLock.acquire();


//        navigationView.setNavigationItemSelectedListener(this);
        adapter = new CoinWalletAdapter(this, wallets);
        rvCoinList.setLayoutManager(new LinearLayoutManager(this));
        rvCoinList.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
//            super.onBackPressed();
        }
    }


    @OnClick({R.id.cl_money, R.id.cl_record, R.id.cl_address, R.id.cl_secure, R.id.cl_function, R.id.cl_setting, R.id.cl_about, R.id.cl_hlep})
    public void click(ConstraintLayout constraintLayout) {

        Intent intent = new Intent();

        switch (constraintLayout.getId()) {
            case R.id.cl_money:
                break;
            case R.id.cl_record:
                intent.setClass(this, TransationRecoderActivity.class);
                startActivity(intent);
                break;
            case R.id.cl_address:
                intent.setClass(this, AddressBookActivity.class);
                startActivity(intent);
                break;
            case R.id.cl_secure:
                /*intent.setClass(this, LockActivity.class);
                startActivity(intent);*/
                ToastUtils.showToast("暂未开放");
                break;
            case R.id.cl_function:
                //从FunctionActivity改为通用了
                intent.setClass(this, UniversalActivity.class);
                startActivity(intent);
                break;
            case R.id.cl_setting:
                intent.setClass(this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.cl_hlep:
                ActivityLauncher.gotoFAQActivity(this);
                break;
            case R.id.cl_about:
                break;
            default:
                break;

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

    }


    @Override
    protected void onResume() {
        super.onResume();
        wallets = WalletApp.queryCurrrentWallet();
        if (wallets != null) {

            TextView tv_wallet_id = drawer.findViewById(R.id.tv_wallet_id);
            String uuid = WalletApp.queryCurrrentAccountId();
            String subsID = uuid;
            if (uuid.length() > 11) {
                //Logger.ds("大于11位: " + subsID);
                subsID = uuid.substring(uuid.length() - 11, uuid.length());
            } else {
                //uuid默认为空字符串了
                //Logger.ds("小于或等于11位: " + subsID);
            }
            //id截取最后的11位
            tv_wallet_id.setText(StringUtil.getResourceStringAndFormat(R.string.wallet_id, subsID));

            adapter.setWallets(wallets);
            adapter.notifyDataSetChanged();
        }

        //Logger.ds("onResume");
    }

    public static void startFromWalletCreate(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.M)
    public void requestDrawOverLays() {
        if (!Settings.canDrawOverlays(MainActivity.this)) {
            Toast.makeText(this, "请为该应用开启悬浮窗权限！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + MainActivity.this.getPackageName()));
            startActivityForResult(intent, 1001);
        } else {
            // Already hold the SYSTEM_ALERT_WINDOW permission, do addview or something.
//            checkPublishPermission();
            //        //设置悬浮框
            Intent floatIntent = new Intent(MainActivity.this, FloatWindowService.class);
            startService(floatIntent);
        }

//
//        //设置悬浮框
//        Intent floatIntent = new Intent(MainActivity.this, FloatWindowService.class);
//        startService(floatIntent);


    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case 1001: {
//                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    resultDrawOverLays();
//                }
//
//
//            }
//        }
//    }

    @TargetApi(Build.VERSION_CODES.M)
    private void resultDrawOverLays() {
        if (!Settings.canDrawOverlays(this)) {
            // SYSTEM_ALERT_WINDOW permission not granted...
            Toast.makeText(this, "请为该应用开启悬浮窗权限", Toast.LENGTH_SHORT).show();
        } else {
            Intent floatIntent = new Intent(MainActivity.this, FloatWindowService.class);
            startService(floatIntent);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

}
